﻿using NPOI.HSSF.UserModel;
using OMG.Fill.Frunit.Model.Ent;
using OMG.Fill.Frunit.Services;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;

namespace OMG.Fill.Frunit.Model.UI.Controllers
{
    public class ReportController : ApiController
    {
        ReportServices reportServices = new ReportServices();
        DictServices dictServices = new DictServices();
        //[ApiActionAuthorize("获取填报基本信息T_Report分页列表对象操作")]
        //[ApiActionException]
        public Pager<List<ReportModel>> PostPageList(ReportQuery query)
        {
            return reportServices.GetPageList(query);
        }
        public Pager<List<ReportModel>> PostReviewPageList(ReportQuery query)
        {
            return reportServices.GetReviewPageList(query);
        }
        //[ApiActionAuthorize("新增填报基本信息T_Report指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Post(ReportEntity model)
        {
            return reportServices.AddInfo(model);
        }
        //[ApiActionAuthorize("修改填报基本信息T_Report指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Put(ReportEntity model)
        {
            return reportServices.UpdateInfo(model);
        }
        //[ApiActionAuthorize("删除填报基本信息T_Report指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Delete(string id)
        {
            return reportServices.DeleteInfo(id);
        }
        //[ApiActionAuthorize("获取填报基本信息T_Report指定对象操作")]
        //[ApiActionException]
        public ReportDataModel Get(string id, string reportCode)
        {
            return reportServices.GetReportData(id, reportCode);
        }
        public ResResult<int> PostUpStatus(ReviewModel model)
        {
            return reportServices.UpStatus(model.Id, model.reportType, model.strMsg);
        }
        /// <summary>
        ///  获取本年和上一年的数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReportDataModel PostData(VegNowModel model)
        {
            return reportServices.GetModel(model);
        }
        public ResResult<List<ReportReview>> GetReportReview(string AreaCode,string FillInYear)
        {
            return reportServices.GetReportReview(AreaCode, FillInYear);
        }

        /// <summary>
        /// 模板下载
        /// </summary>
        /// <param name="ReportCode"></param>
        /// <returns></returns>
        public MemoryStream GetExcelTemplate(string ReportCode)
        {
            //MemoryStream ms = new MemoryStream();
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string templateName = "";
            string sheetName = "";
            switch (ReportCode)
            {
                case "FruTecPromotion":
                    templateName = fileIndex + @"Excel\FruTecPromotion.xls";//模板文件路径
                    sheetName = "Sheet1";
                    break;
                case "FruExport":
                    templateName = fileIndex + @"Excel\FruExport.xls";//模板文件路径
                    sheetName = "Sheet1";
                    break;
                case "FruProsecution":
                    templateName = fileIndex + @"Excel\FruProsecution.xls";//模板文件路径
                    sheetName = "Sheet1";
                    break;
                case "FruProSurvey":
                    templateName = fileIndex + @"Excel\FruDownload.xls";//模板文件路径
                    sheetName = "FruProSurvey";
                    break;
                case "FruProSeason":
                    templateName = fileIndex + @"Excel\FruDownload.xls";//模板文件路径
                    sheetName = "FruProSeason";
                    break;
            }
            FileStream file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet(sheetName) as HSSFSheet;//读取模板所在sheet位置
            sheet.CopyTo(workbook, "Sheet1", true, true);
           var tem =  workbook.GetSheetAt(0);
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                file.Close();
                return ms;
            }

        }
        /// <summary>
        /// 模板下载响应
        /// </summary>
        /// <param name="ReportCode"></param>
        public void GetTemplateData(string ReportCode)
        {
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            string strFileName = "";
            switch (ReportCode)
            {
                case "FruTecPromotion":
                    strFileName = "（五）水果技术推广机构及人员情况表.xls";//文件名称
                    break;
                case "FruExport":
                    strFileName = "（三）水果外销统计表.xls";//文件名称
                    break;
                case "FruProsecution":
                    strFileName = "（四）水果生产经营实体情况表.xls";//文件名称
                    break;
                case "FruProSurvey":
                    strFileName = "（二）主要水果生产情况年度面积产量表.xls";//文件名称
                    break;
                case "FruProSeason":
                    strFileName = "（一）主要水果生产情况季度统计表.xls";//文件名称
                    break;
            }
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
            curContext.Response.BinaryWrite(GetExcelTemplate(ReportCode).GetBuffer());
            curContext.Response.End();
        }

        /// <summary>
        /// 静态表导入数据
        /// </summary>
        /// <param name="ReportCode"></param>
        /// <param name="AreaCode"></param>
        /// <returns></returns>
        public List<ResResult<int>> PostImportData(string ReportCode, string AreaCode)
        {
            List<ResResult<int>> obj = new List<ResResult<int>>();
            ResResult<int> SingleObj = new ResResult<int>();
            HttpContext curContext = HttpContext.Current;
            HttpFileCollection files = curContext.Request.Files;
            if (curContext.Request.Files.Count != 0)
            {
                HttpPostedFile upfile = files[0];
                if (upfile != null && upfile.ContentLength > 0)
                {
                    string temppath = curContext.Server.MapPath("~/App_Data/temppath");
                    if (!Directory.Exists(temppath))//判断文件夹是否存在 
                    {
                        Directory.CreateDirectory(temppath);//不存在则创建文件夹 
                    }
                    string filetype = Path.GetExtension(upfile.FileName);
                    string filenewName = Guid.NewGuid().ToString().Replace("-", "") + filetype;
                    string strpath = Path.Combine(temppath, filenewName);
                    upfile.SaveAs(strpath);

                    switch (ReportCode)
                    {
                        //蔬菜技术推广机构及人员情况统计表
                        case "FruTecPromotion":
                            FruTecPromotionServices fruTecPromotionServices = new FruTecPromotionServices();
                            var TecList = fruTecPromotionServices.ExcelToModel(strpath, filetype, "", 4);
                            foreach (var item in TecList)
                            {
                                string FillInYear = dictServices.GetKey(item.year);
                                if (fruTecPromotionServices.CheckRepCreate(ReportCode, AreaCode, FillInYear))
                                {
                                    SingleObj.status = -1;
                                    SingleObj.message = item.year + "的报表没有填报数据！！";
                                    obj.Add(SingleObj);
                                }
                                else
                                {
                                    string ReportId = fruTecPromotionServices.GetReportId(ReportCode, AreaCode, FillInYear);
                                    item.ReportId = ReportId;
                                    //判断list中是否初始化过报表
                                    if (fruTecPromotionServices.CheckRepCount(ReportId))
                                    {
                                        //没初始化过进来
                                        SingleObj = fruTecPromotionServices.AddInfo(item);
                                    }
                                    else
                                    {
                                        SingleObj = fruTecPromotionServices.UpdateInfo(item);
                                    }
                                    SingleObj.status = DefaultKey.SuccessResult; ;
                                    SingleObj.message = item.year + "数据导入成功！！";
                                    reportServices.UpStatus(ReportId, "2", "");
                                    obj.Add(SingleObj);
                                }
                            }
                            break;
                        //蔬菜外销情况调查表
                        case "FruExport":
                            FruExportServices FruExportServices = new FruExportServices();
                            var ExpList = FruExportServices.ExcelToModel(strpath, filetype, "", 3);
                            foreach (var item in ExpList)
                            {
                                string FillInYear = dictServices.GetKey(item.year);
                                if (FruExportServices.CheckRepCreate(ReportCode, AreaCode, FillInYear))
                                {
                                    SingleObj.status = -1;
                                    SingleObj.message = item.year + "的报表没有填报数据！！";
                                    obj.Add(SingleObj);
                                }
                                else
                                {
                                    string ReportId = FruExportServices.GetReportId(ReportCode, AreaCode, FillInYear);
                                    item.ReportId = ReportId;
                                    //判断list中是否初始化过报表
                                    if (FruExportServices.CheckRepCount(ReportId))
                                    {
                                        //没初始化过进来
                                        SingleObj = FruExportServices.AddInfo(item);
                                    }
                                    else
                                    {
                                        SingleObj = FruExportServices.UpdateInfo(item);
                                    }
                                    SingleObj.status = DefaultKey.SuccessResult; ;
                                    SingleObj.message = item.year + "数据导入成功！！";
                                    reportServices.UpStatus(ReportId, "2", "");
                                    obj.Add(SingleObj);
                                }
                            }
                            break;
                        //蔬菜生产经营实体情况表
                        case "FruProsecution":
                            FruProsecutionServices fruProsecutionServices = new FruProsecutionServices();
                            var ProseList = fruProsecutionServices.ExcelToModel(strpath, filetype, "", 4);
                            foreach (var item in ProseList)
                            {
                                string FillInYear = dictServices.GetKey(item.year);
                                if (fruProsecutionServices.CheckRepCreate(ReportCode, AreaCode, FillInYear))
                                {
                                    SingleObj.status = -1;
                                    SingleObj.message = item.year + "的报表没有填报数据！！";
                                    obj.Add(SingleObj);
                                }
                                else
                                {
                                    string ReportId = fruProsecutionServices.GetReportId(ReportCode, AreaCode, FillInYear);
                                    item.ReportId = ReportId;
                                    //判断list中是否初始化过报表
                                    if (fruProsecutionServices.CheckRepCount(ReportId))
                                    {
                                        //没初始化过进来
                                        SingleObj = fruProsecutionServices.AddInfo(item);
                                    }
                                    else
                                    {
                                        SingleObj = fruProsecutionServices.UpdateInfo(item);
                                    }
                                    SingleObj.status = DefaultKey.SuccessResult; ;
                                    SingleObj.message = item.year + "数据导入成功！！";
                                    reportServices.UpStatus(ReportId, "2", "");
                                    obj.Add(SingleObj);
                                }
                            }
                            break;
                    }
                    Directory.Delete(temppath, true);
                }
            }
            return obj;
        }

        /// <summary>
        /// 动态表导入数据
        /// </summary>
        /// <param name="ReportId"></param>
        /// <returns></returns>
        public List<ResResult<int>> PostImportDataTwo(string ReportId)
        {
            List<ResResult<int>> obj = new List<ResResult<int>>();
            ResResult<int> SingleObj = new ResResult<int>();
            HttpContext curContext = HttpContext.Current;
            HttpFileCollection files = curContext.Request.Files;
            if (curContext.Request.Files.Count != 0)
            {
                HttpPostedFile upfile = files[0];
                if (upfile != null && upfile.ContentLength > 0)
                {
                    string temppath = curContext.Server.MapPath("~/App_Data/temppath");
                    if (!Directory.Exists(temppath))//判断文件夹是否存在 
                    {
                        Directory.CreateDirectory(temppath);//不存在则创建文件夹 
                    }
                    string filetype = Path.GetExtension(upfile.FileName);
                    string filenewName = Guid.NewGuid().ToString().Replace("-", "") + filetype;
                    string strpath = Path.Combine(temppath, filenewName);
                    upfile.SaveAs(strpath);
                    FruProSurveyServices fruProSurveyServices = new FruProSurveyServices();
                    var ProsurveyList = fruProSurveyServices.ExcelToModel(strpath, filetype, "", 2);
                    //检查报表是否初始化过
                    if (fruProSurveyServices.CheckRepCount(ReportId))
                    {
                        //没初始化进来
                        List<FruProSurveyEntity> templist = fruProSurveyServices.GetTabContent(ReportId, 0);
                        fruProSurveyServices.AddInfo(templist);
                    }
                    foreach (var item in ProsurveyList)
                    {
                        item.ReportId = ReportId;
                        reportServices.UpStatus(ReportId, "2", "");
                        SingleObj = fruProSurveyServices.UpdateInfo(item);
                        SingleObj.status = DefaultKey.SuccessResult;
                        SingleObj.message = "数据导入成功！！";
                        obj.Add(SingleObj);
                    }
                    Directory.Delete(temppath, true);
                }
            }
            return obj;
        }
        /// <summary>
        /// 数据导入
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> PostExportExcel(ReportEntity model)
        {
            // Check whether the POST operation is MultiPart?  
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            // Prepare CustomMultipartFormDataStreamProvider in which our multipart form  
            // data will be loaded.  
            string fileSaveLocation = HttpContext.Current.Server.MapPath("~/Upload");
            CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
            List<string> files = new List<string>();

            try
            {
                // Read all contents of multipart message into CustomMultipartFormDataStreamProvider.  
                await Request.Content.ReadAsMultipartAsync(provider);

                foreach (MultipartFileData file in provider.FileData)
                {
                    files.Add(Path.GetFileName(file.LocalFileName));
                }

                // Send OK Response along with saved file names to the client.  
                return Request.CreateResponse(HttpStatusCode.OK, files);
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
        public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
        {
            public CustomMultipartFormDataStreamProvider(string path) : base(path) { }

            public override string GetLocalFileName(HttpContentHeaders headers)
            {
                return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
            }
        }
    }
    public class ReviewModel
    {
        public string Id { get; set; }
        public string reportType { get; set; }
        public string strMsg { get; set; }
    }

}